package com.rrd.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * @author songxin
 */
public class UserCreditTypeUDF extends UDF{

    public Text evaluate(
            String currentDate,
            String auditCreateTime,
            String auditTime,
            Integer auditStatus,
            String auditExpireTime,
            String isLoanAuditPassed,
            String loanAuditTime) {
        /*
        1. 机审相关的进件类型
            首次：没有过进件记录的用户
            机审被拒：在计算当天机审被拒的用户
            额度过期：在计算当天之前额度过期的用户
            其他：机审通过等
         2. 放款审核相关的进件类型
            放款审核被拒：在计算当天之前放款审核被拒的用户
         判断逻辑：
            根据机审相关字段，判断用户所属的机审相关进件类型，并记录更新时间
            根据放款审核相关字段，判断用户所属的放款审核相关的进件类型，并记录更新时间
            取两者中更新时间较新的作为用户实际的进件类型
         */
        // 判断机审相关的进件类型
        String defaultCreditType = "OTHER";
        String auditCreditType = defaultCreditType;
        String loanAuditCreditType = defaultCreditType;
        String auditUpdateTime = currentDate;
        Integer auditSuccessStatus = 2;
        Integer auditFailedStatus = 3;
        String notPassed = "false";

        if (auditCreateTime == null) {
            // 没有过进件记录，认为客群为首次
            auditCreditType = "FIRST";
        } else if (auditTime != null && auditStatus != null) {
            if (auditStatus.equals(auditFailedStatus)) {
                // 审核失败
                auditCreditType = "AUDIT_FAILED";
                auditUpdateTime = auditTime;
            } else if (auditStatus.equals(auditSuccessStatus) && auditExpireTime != null && auditExpireTime.compareTo(currentDate) <= 0) {
                // 额度过期
                auditCreditType = "AUDIT_EXPIRED";
                auditUpdateTime = auditExpireTime;
            }
        }
        if (notPassed.equals(isLoanAuditPassed)) {
            loanAuditCreditType = "LOAN_AUDIT_FAILED";
        }
        Text result = new Text();
        if (!defaultCreditType.equals(loanAuditCreditType) && loanAuditTime != null && loanAuditTime.compareTo(auditUpdateTime) >= 0) {
            result.set(loanAuditCreditType);
        } else {
            result.set(auditCreditType);
        }
        return result;
    }
}
